<template>
  <div id="users">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->

    <el-input placeholder="请输入内容" v-model="inputValue" class="input-with-select">
      <el-button @click="searchUser" slot="append" icon="el-icon-search"></el-button>
    </el-input>
    <!-- 添加按鈕 -->
    <el-button type="success" plain @click="dialogFormVisible">添加用户</el-button>

    <!-- table栏 -->
    <el-table border :data="userList">
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column label="用户状态">
        <template v-slot:default="obj">
          <el-switch
            @change="changeState(obj.row.id,obj.row.mg_state)"
            v-model="obj.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot:default = "{ row }">
          <el-button size="small" type="primary" @click= 'editShow(row)' plain icon="el-icon-edit"></el-button>
          <el-button size="small" type="danger" @click="delshow(row.id)" plain icon="el-icon-delete"></el-button>
          <el-button size="small" type="success" @click="showAllot(row)" plain icon="el-icon-check">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 添加用户框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="40%"
      @close = "closeDialog">
        <el-form ref="form" :rules="rules" :model="form" label-width="80px">
          <el-form-item label='用户名' prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label='密码'  prop="password">
            <el-input type="password" v-model="form.password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label='邮箱' prop="email">
            <el-input v-model="form.email" placeholder="邮箱"></el-input>
          </el-form-item>
          <el-form-item label='手机号' prop="mobile">
            <el-input v-model="form.mobile" placeholder="手机号"></el-input>
          </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click= 'present'>确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户 -->
     <el-dialog
      title="添加用户"
      :visible.sync="editVisible"
      width="40%">
        <el-form ref="editform" :rules="rules" :model="editform" label-width="80px">
          <el-form-item label='用户名' prop="username">
            <el-tag type="info">{{editform.username}}</el-tag>
          </el-form-item>
          <el-form-item label='邮箱' prop="email">
            <el-input v-model="editform.email" placeholder="邮箱"></el-input>
          </el-form-item>
          <el-form-item label='手机号' prop="mobile">
            <el-input v-model="editform.mobile" placeholder="手机号"></el-input>
          </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click= 'editUser'>确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配用户 -->
    <el-dialog
      title="添加用户"
      :visible.sync="allotVisible"
      width="40%">
        <el-form :model="allotform" label-width="80px">
          <el-form-item label='用户名'>
            <el-tag type="info">{{allotform.username}}</el-tag>
          </el-form-item>
          <el-form-item label='角色列表'>
            <el-select  v-model="allotform.rid" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotVisible = false">取 消</el-button>
        <el-button type="primary" @click = 'usermod'>确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      inputValue: '',
      userList: [],
      mg_state: '',
      query: '',
      pagenum: 1,
      pagesize: 2,
      total: 0,
      dialogVisible: false,
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      rules: { // 配置校验规则
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: ['blur', 'change'] }
        ],
        email: [
          { type: 'email', message: '请输入邮箱', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入手机号码', trigger: ['blur', 'change'] }

        ]
      },
      editVisible: false,
      editform: { // 修改
        username: '',
        password: '',
        mobile: '',
        id: ''
      },
      allotVisible: false,
      options: [],
      allotform: {
        username: '',
        id: '',
        rid: ''
      }

    }
  },
  created () { // 进入页面直接渲染
    this.render()
  },
  methods: {
    changeState (id, type) { // 滑块
      this.$axios.put(`users/${id}/state/${type}`).then(res => {
        const { meta } = res
        if (meta.status === 200) {
          this.$message.success(meta.msg)
        } else {
          this.$message.error(meta.msg)
        }
      })
    },
    render () { // 渲染
      this.$axios
        .get('users', {
          params: {
            query: this.query,
            pagenum: this.pagenum,
            pagesize: this.pagesize
          }
        })
        .then(result => {
          const { meta, data } = result
          if (meta.status === 200) {
            this.userList = data.users
            this.total = data.total
          } else {
            this.$message.error(meta.msg)
          }
        })
    },
    handleSizeChange (val) { // 每页
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.pagenum = 1
      this.render()
    },
    handleCurrentChange (val) { // 当前页
      // console.log(`当前页: ${val}`)
      this.pagenum = val
      this.render()
    },
    searchUser () { // 搜索
      this.query = this.inputValue
      console.log(this.query)

      this.pagenum = 1
      this.render()
    },
    dialogFormVisible () { // 添加框
      this.dialogVisible = true
    },
    async present () { // 提交
      try {
        await this.$refs.form.validate()
        const { meta, data } = await this.$axios.post('users', {
          username: this.form.username,
          password: this.form.password,
          email: this.form.email,
          mobile: this.form.mobile
        })
        console.log(meta, data)

        if (meta.status === 201) {
          this.$message.success(meta.msg)
          this.dialogVisible = false
          this.pagenum = Math.ceil(++this.total / this.pagesize)
          this.render()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    closeDialog () { // 重置
      this.$refs.form.resetFields()
    },
    async delshow (id) { // 删除
      try {
        console.log(id)
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', { type: 'warning' })
        const { meta, data } = await this.$axios.delete(`users/${id}`)
        console.log(meta, data)

        if (meta.status === 200) {
          this.$message.success(meta.msg)
          if (this.userList.length === 1 && this.pagenum > 1) {
            this.pagenum--
          }
          this.render()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    editShow (row) { // 点击显示修改框
      this.editVisible = true
      this.editform.username = row.username
      this.editform.email = row.email
      this.editform.mobile = row.mobile
      this.editform.id = row.id
    },
    async editUser () { // 修改用户
      // 校验表单
      const { id, email, mobile } = this.editform
      try {
        await this.$refs.editform.validate()
        const { meta } = await this.$axios.put(`users/${id}`, { email, mobile })
        console.log(meta)
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          this.editVisible = false
          this.render()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    async showAllot (row) { // 显示分配用户
      this.allotVisible = true
      const { id, username } = row
      this.allotform.username = username
      this.allotform.id = id
      const resUser = await this.$axios.get(`users/${id}`)
      if (resUser.meta.status === 200) {
        const rid = resUser.data.rid
        this.allotform.rid = rid === -1 ? '' : rid
      }
      const { meta, data } = await this.$axios.get('roles')
      // console.log(meta, data)
      if (meta.status === 200) {
        this.options = data
        // console.log(this.options)
      } else {
        this.$message.error(meta.msg)
      }
    },
    async usermod () { // 分配用户
      const { id, rid } = this.allotform
      const { meta } = await this.$axios.put(`users/${id}/role`, { rid })

      if (meta.status === 200) {
        this.$message.success(meta.msg)
        this.allotVisible = false
        this.render()
      } else {
        this.$message.error(meta.msg)
      }
    }
  }
}
</script>

<style lang = 'less' scoped>
#users {

  .input-with-select {
    width: 300px;
    margin: 0 20px 20px 0;
  }
}
</style>
